package com.dfbz.netctoss.config;

//import com.dfbz.netctoss.cache.RedisCacheManage;
import com.dfbz.netctoss.realm.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * 1.创建shiroFilter
 * 2.创建安全管理器
 * 3.创建realm
 */
@Configuration
public class SpringShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //配置受限资源
        HashMap<String, String> map = new HashMap<>();
        map.put("/common/login","anon"); //无需认证
        map.put("/styles/**","anon");
        map.put("/layer/**","anon");
        map.put("/js/**","anon");
        map.put("/jquery/**","anon");
        map.put("/images/**","anon");
        map.put("/vue/**","anon");
        map.put("/**","authc");//需要认证和授权
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        //默认认证界面路径
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    @Bean
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法为MD5
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        //开启缓存
//        customerRealm.setCacheManager(new RedisCacheManage());
//        customerRealm.setCachingEnabled(true);
//        customerRealm.setAuthenticationCachingEnabled(true);
//        customerRealm.setAuthenticationCacheName("authenticationCache");
//        customerRealm.setAuthorizationCachingEnabled(true);
//        customerRealm.setAuthorizationCacheName("authorizationCache");


        return customerRealm;


    }
}
